﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;

using EFERP;
using HRM.DICTIONARY.DAL;
using HRM.DICTIONARY.BLL;
using DevExpress.Utils;

namespace HRM.DICTIONARY.LOGINUI
{
    public partial class xfrmLogin : DevExpress.XtraEditors.XtraForm
    {
        SystemLogin myLogin;
        private int solanDangNhap = 0;

        private WaitDialogForm dlg = null;
        public void SetWaitDialogCaption(string fCaption, string MainCaption)
        {
            if (this.dlg != null)
            {
                this.dlg.Caption = fCaption;
            }
            else
            {
                CreateWaitDialog(fCaption, MainCaption);
                if (this.dlg != null)
                {
                    this.dlg.Caption = fCaption;
                }
            }
        }
        public void CreateWaitDialog(string fCaption, string MainCaption)
        {
            if (fCaption == "")
            {
                this.dlg = new WaitDialogForm(MainCaption, "HỆ THỐNG QUẢN LÝ NHÂN SỰ");
                this.dlg.StartPosition = FormStartPosition.CenterScreen;
            }
            else
            {
                this.dlg = new WaitDialogForm(MainCaption, fCaption);
                this.dlg.StartPosition = FormStartPosition.CenterScreen;
            }
        }
        protected virtual void DoHide()
        {
            //base.OnLoad(EventArgs.Empty);
            if (this.dlg != null)
            {
                this.dlg.FormClosing += new FormClosingEventHandler(this.dlg_FormClosing);
                this.dlg.Close();
            }
        }
        private void dlg_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.dlg.Dispose();
            this.dlg = null;
        }

        public xfrmLogin()
        {
            SetWaitDialogCaption("Đang tải dữ liệu..." , "");
            InitializeComponent();
            this.txtUserName.Focus();
            myLogin = new SystemLogin();
            this.readRemember();
            DoHide();
        }

        private void readRemember()
        {
            DataTable table = new DataTable("account");
            table.Columns.Add("user");
            table.Columns.Add("pass");
            FileInfo info = new FileInfo(Application.StartupPath + @"\account.xml");
            if (info.Exists)
            {
                this.chxRemember.Checked = true;
                DataSet set = new DataSet();
                set.Tables.Add(table);
                try
                {
                    set.ReadXml(Application.StartupPath + @"\account.xml");
                    if (set.Tables[0].Rows.Count > 0)
                    {
                        this.txtUserName.Text = StaticVariable.Decrypt(set.Tables[0].Rows[0]["user"].ToString(), StaticVariable.PasswKeyToEncrypt);
                        if (this.txtPassword.Text != "")
                            this.txtPassword.Text = StaticVariable.Decrypt(set.Tables[0].Rows[0]["pass"].ToString(), StaticVariable.PasswKeyToEncrypt);
                    }
                }
                catch (Exception exception)
                {
                    XtraMessageBox.Show(this, exception.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                if (this.txtPassword.Text != "")
                {
                    this.chxRemember.Checked = true;
                }
                else
                {
                    this.chxRemember.Checked = false;
                }
            }
        }
        private void saveRemember()
        {
            try
            {
                DataSet set = new DataSet();
                DataTable table = new DataTable("account");
                table.Columns.Add("user");
                table.Columns.Add("pass");
                table.Rows.Clear();
                table.Rows.Add(new object[] { 
                    StaticVariable.ToEncrypt(this.txtUserName.Text, StaticVariable.PasswKeyToEncrypt), 
                    StaticVariable.ToEncrypt(this.txtPassword.Text, StaticVariable.PasswKeyToEncrypt) 
                });
                set.Tables.Add(table);
                set.WriteXml(Application.StartupPath + @"\account.xml");
            }
            catch (Exception exception)
            {
                XtraMessageBox.Show(this, exception.Message, "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
        private void saveNullRemember()
        {
            try
            {
                DataSet set = new DataSet();
                DataTable table = new DataTable("account");
                table.Columns.Add("user");
                table.Columns.Add("pass");
                table.Rows.Clear();
                table.Rows.Add(new object[] { 
                    StaticVariable.ToEncrypt(this.txtUserName.Text, StaticVariable.PasswKeyToEncrypt), ""
                });
                set.Tables.Add(table);
                set.WriteXml(Application.StartupPath + @"\account.xml");
            }
            catch (Exception exception)
            {
                XtraMessageBox.Show(this, exception.Message, "Th\x00f4ng B\x00e1o", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            SetWaitDialogCaption("Đang kiểm tra dữ liệu...", "Vui lòng đợi trong giấy lát...");
            DateTime LoginDate = System.DateTime.Now;
            this.btnLogin.Enabled = false;
            if (this.txtUserName.Text.Trim() == "")
            {
                this.txtUserName.ErrorText = "Bạn chưa nhập tài khoản!";
                this.Err.SetIconAlignment(this.txtUserName, ErrorIconAlignment.MiddleRight);
                this.btnLogin.Enabled = true;
                this.txtUserName.Focus();
                Cursor.Current = Cursors.Default;
                DoHide();
            }
            else
            {
                SetWaitDialogCaption("Đang kiểm tra dữ liệu đăng nhập...", "Vui lòng đợi trong giấy lát...");
                bool KQ = myLogin.CheckAccount(this.txtUserName.Text, this.txtPassword.Text);
                if (!KQ)
                {
                    XtraMessageBox.Show(this, myLogin.ErrMsg, "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    this.solanDangNhap++;
                    if (this.solanDangNhap >= 3)
                    {
                        DoHide();
                        XtraMessageBox.Show(this, "Bạn đã nhập sai quá số lần cho phép!\n\nPhần mềm sẽ tự động kết thúc!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        base.Close();
                        Cursor.Current = Cursors.Default;
                        Environment.Exit(0);
                        Application.ExitThread();
                    }
                }
                else
                {
                    SetWaitDialogCaption("Đang lưu vào hệ thống...", "Vui lòng đợi trong giấy lát...");
                    if (StaticVariable.UserLogin.management == 0) StaticVariable.UserRoleCode = RoleCode.None;
                    else if (StaticVariable.UserLogin.management == 1) StaticVariable.UserRoleCode = RoleCode.BranchCode;
                    else if (StaticVariable.UserLogin.management == 2) StaticVariable.UserRoleCode = RoleCode.DepartmentCode;
                    else StaticVariable.UserRoleCode = RoleCode.GroupCode;

                    if (this.chxRemember.Checked)
                    {
                        this.saveRemember();
                    }
                    else
                    {
                        this.saveNullRemember();
                    }
                    DoHide();
                    base.Hide();
                    Cursor.Current = Cursors.Default;
                    base.Close();
                }
                this.btnLogin.Enabled = true;
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnLogin_Click(sender, e);
            }
        }
    }
}